<template>
    <d2-container>
        <el-form :inline="true" :model="dataSearch" ref="dataSearch">

            <el-form-item label="学生" prop="name">
                <el-input v-model="dataSearch.name" placeholder="请输入学生姓名" size="mini"></el-input>
            </el-form-item>

            <el-form-item label="学号" prop="studentId">
                <el-input v-model="dataSearch.studentId" placeholder="请输入学生学号" size="mini"></el-input>
            </el-form-item>

            <el-form-item label="性别：" prop="gender">
                <el-select v-model="dataSearch.gender" placeholder="请选择性别" size="mini">
                    <el-option
                            v-for="item of this.options.genderOption"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>

             <el-form-item label="校区" prop="school" v-if='showSchool'>
                <el-select
                        v-model="dataSearch.school"
                        filterable
                        placeholder="请选择校区"
                        @change="schoolSelected"
                        :disabled="disabled"
                >
                    <el-option
                            v-for="item in schoolList"
                            :key="item._id"
                            :label="item.name"
                            :value="item._id"
                    ></el-option>
                </el-select>
            </el-form-item>

             <el-form-item label="学生状态：" prop="type">
        <el-radio-group v-model="dataSearch.status" @change='changeStatus'>
          <el-radio :label="-1">全部</el-radio>
          <el-radio :label="0">在读</el-radio>
          <el-radio :label="1">停课</el-radio>
          <el-radio :label="2">流失</el-radio>
        </el-radio-group>
        <el-form-item>
        <el-button type="primary" @click="search" style='margin-left: 30px'>
          <d2-icon name="search" />查询
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="formReset">
          <d2-icon name="refresh" />重置
        </el-button>
      </el-form-item>
    </el-form-item>


        </el-form>
        <div style="margin-bottom: 20px;display: block">
        
            <a href="#/student-new">
                <el-button type="primary" style="margin-right:50px" icon="el-icon-plus" size="mini">新建学生</el-button>
            </a>

                <el-button type="secondary" style="margin-right: 10px"  size="mini" @click='exportList'>导出列表</el-button>
                <el-button type="secondary" style="margin-right: 10px"  size="mini" onclick="filefile.click()">批量导入</el-button>
                <input type="file" @change="uploadTemplate(this)" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" style="display:none" id='filefile'></input>

                <el-button type="secondary" style="margin-right: 10px"  size="mini" @click='downloadTemplate'>下载模板</el-button>

            </div>

        <el-table :data="dataList" border style="width: 100%;margin-top: 10px" :height='600'>
            <el-table-column prop="name" label="学生姓名"></el-table-column>
            <el-table-column prop="studentId" label="学号"></el-table-column>
            <el-table-column prop="genderText" label="性别"></el-table-column>
            <el-table-column prop="schoolText" label="校区"></el-table-column>
            <el-table-column prop="contact" label="联系方式" >
                 <template slot-scope="scope" >
                        <div style="white-space: pre-line;">{{dataList[scope.$index].contact}}</div>
                </template>
            </el-table-column>
            <el-table-column  label="课程">
                <template slot-scope="scope" >
                        <div style="white-space: pre-line;">{{dataList[scope.$index].course}}</div>
                </template>
            </el-table-column>
            <el-table-column  label="班级">
                <template slot-scope="scope" >
                        <div style="white-space: pre-line;">{{dataList[scope.$index].class}}</div>
                </template>
            </el-table-column>
            <el-table-column prop="statusText" label="状态"></el-table-column>
            <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                    <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
                    <el-button @click="deleteClick(scope.row)" type="text" size="small">删除</el-button>
                </template>
            </el-table-column>
           
        </el-table>

        <el-pagination
                background
                layout="total,sizes,prev, pager, next,jumper"
                :page-size="pageSize"
                :current-page="currentPage"
                :total="total"
                @current-change="handleCurrentChange"
                @size-change="handlerSizeChange"
                @next-click="handleNextPage"
                @prev-click="handlePrevClick"
        ></el-pagination>
    </d2-container>
</template>
<style>
 .el-table .cell .el-table-column {
　　white-space: pre-line;
}   

</style>
<script>
    import request from "@/plugin/axios";
    import {mapState} from 'vuex'
    import excel from "@/libs/util.excel"
// import Blob from './excel/Blob.js'
// import Export2Excel from './excel/Export2Excel.js'
    export default {
        data() {
            return {
                dataSearch: {
                    name: undefined,
                    studentId: undefined,
                    gender: undefined,
                    searchClass: undefined,
                    status : -1,
                    school : undefined
                },
                showSchool : false,
                headquarter : 0,
                options: {
                    genderOption: [
                        {
                            label: '男',
                            value: 0
                        },
                        {
                            label: '女',
                            value: 1
                        }
                    ]
                },
                dataList: [],
                total: 100,
                pageSize: 20,
                currentPage: 1,
                excelData : [],
                loading : false,
                schoolList : []
            };
        },
        computed: {
            ...mapState('d2admin/user', ['info'])
        },
        methods: {
            formSubmit() {
                this.dataSearch.page = this.currentPage;
                this.dataSearch.pageSize = this.pageSize;
                this.getDataList(this.dataSearch);
            },
            
            handleClick(e) {
                // this.$router.open({path: })
                // let url = 'http://localhost:8080/#/student-detail?id=' + e._id
                // window.open(url , '_blank');
                this.$router.push({path: '/student-detail?id=' + e._id})
            },
            deleteClick(e){
                this.$confirm('如果该学生已经有课程订单，请先再次确认是否删除。如果要删除，请先把该学生课程停课。','确定要删除该学生吗？',{ confirmButtonText : '确定',
          cancelButtonText : '取消'
                }).then(res =>{
                    request({
                          url: "/student/deleteStudent",
                          method: "post",
                          data: {_id:e._id}
                        }).then(res => {
                          if (res.code == 200) {
                              this.$message({
                                message: "删除成功"
                              });
                              this.getDataList(this.dataSearch)
                          }
                        })
                })
            },
            handleCurrentChange(currentPage) {
                this.currentPage = currentPage
                this.dataSearch.page = this.currentPage;
                this.dataSearch.pageSize = this.pageSize;
                this.getDataList(this.dataSearch);
            },
            handlerSizeChange(pageSize) {
                this.pageSize = pageSize
                this.dataSearch.page = this.currentPage;
                this.dataSearch.pageSize = this.pageSize;
                this.getDataList(this.dataSearch);
            },
            handleNextPage() {
                this.currentPage = this.currentPage + 1
                this.dataSearch.page = this.currentPage;
                this.dataSearch.pageSize = this.pageSize;
                this.getDataList(this.dataSearch);
            },
            handlePrevClick() {
                this.currentPage = this.currentPage - 1
                this.dataSearch.page = this.currentPage;
                this.dataSearch.pageSize = this.pageSize;
                this.getDataList(this.dataSearch);
            },

            changeStatus(){
                this.getDataList(this.dataSearch)
            },

            search(){
                this.getDataList(this.dataSearch)
            },
            formReset(){
                this.dataSearch = {
                    name: undefined,
                    studentId: undefined,
                    gender: undefined,
                    searchClass: undefined,
                    status : -1
                }
                this.getDataList(this.dataSearch)
            },

            getDataList(data) {
                let school;
                let _class;
                this.info.role.forEach((value) => {
                    if (value.name === 'school') {
                        school = this.info.school.map(value => value._id);
                        data.school = school;
                    }
                });

                console.log(this.school.schoolType,'sss',this.school)
                if(this.school.schoolType == 2){
                    this.dataSearch.limitSchool = this.info.school.map(value => value._id);
                    data.limitSchool = this.dataSearch.limitSchool;
                }else if(this.school.schoolType ==3){
                    this.dataSearch.limitSchool = this.info.school.map(value => value._id);
                    data.limitSchool = this.dataSearch.limitSchool;
                }
                // data.kkk = this.school

                let index1 = this.rights.indexOf('root') == -1
                let index2 = this.rights.indexOf('授课老师') != -1
                let index4 = this.rights.indexOf('教务老师') != -1
                let index3 = this.rights.indexOf('教务中心') == -1
                index2 = index2 || index4
                if ((index1) && (index2)){
                    if (index3){
                        data.teacher = this.staff
                    }
                }
                else{
                    if (this.headquarter == 1){
                        data.limitSchool = this.dataSearch.school
                    }
                }
                request({
                    url: "/student/getStudentList",
                    method: "post",
                    data: data
                }).then(res => {
                    this.dataList = [];
                    this.dataList = res.data.students;
                    // res.data.students.forEach((value, index) => {
                    //     this.dataList[index]['class'] = value.class.join(',')
                    //     this.dataList[index].isNewStudent = value.isNewStudent==0?'否':'是'
                    // });
                    this.total = res.data.total;
                    this.currentPage = res.data.currentPage;
                    // console.log(res)
                })
            },
        
            




    
            downloadTemplate(){
                let columns = [{label:'学生名字',prop:'name'},{label:'学号',prop:'number'},{label:'性别',prop:'gender'},{label:'生日',prop:'birthday'},{label:'手机',prop:'cellphone'},{label:'地址',prop:'address'},{label:'公立学校',prop:'publicSchool'},{label:'家长1姓名',prop:'parent1'},
                    {label:'家长1关系',prop:'parent1Relation'},{label:'家长1手机',prop:'parent1Cellphone'},{label:'家长2姓名',prop:'parent2'},{label:'家长2关系',prop:'parent2Relation'},{label:'家长2手机',prop:'parent2Cellphone'},
                    {label:'班级1名称',prop:'class1'},{label:'班级1付费方式',prop:'class1Type'},{label:'班级1剩余课时',prop:'class1amount'},{label:'班级1有效期',prop:'class1ValidDate'},{label:'班级1单课价格',prop:'class1Avg'},
                    {label:'班级2名称',prop:'class2'},{label:'班级2付费方式',prop:'class2Type'},{label:'班级2剩余课时',prop:'class2amount'},{label:'班级2有效期',prop:'class2ValidDate'},{label:'班级2单课价格',prop:'class2Avg'}]

                let data =  [{name:'张三',number:'11（可不填）',gender:'0（0-男，1-女)',birthday:'2010.02.02',cellphone:'13501234567',publicSchool:'长哈路小学',parent1:'张妈',parent1Relation:'妈妈',parent1Cellphone:'13501234567',
                    parent2:'张爸',parent2Relation:'爸爸',parent2Cellphone:'13501234567',class1:'初级班1(名字必须正确，否则无法导入)',class1Type:'0(0-按课次，1-按小时，2-包月)',class1ValidDate:'2019.11.22(不填为无有效期)',class1Avg:'300(务必填写，否则无法计算授课提成)',class1amount:10,class2:'没有更多可空白'}]

                excel.export(columns,data,'学生批量导入模板')


            },

            exportList(){
                let school;
                let _class;
                let data = {}
                
                //  if(this.school.headquarter != 1 ){
                //     this.dataSearch.limitSchool = this.info.school.map(value => value._id);
                //     data.limitSchool = this.dataSearch.limitSchool;
                // }
                // else{
                //     this.dataSearch.limitSchool = []
                //     // data.limitSchool
                // }
                this.dataSearch.limitSchool = this.info.school.map(value => value._id);
                data.limitSchool = this.dataSearch.limitSchool;

                let index1 = this.rights.indexOf('root') == -1
                let index2 = this.rights.indexOf('授课老师') != -1
                let index4 = this.rights.indexOf('教务老师') != -1
                let index3 = this.rights.indexOf('教务中心') == -1
                index2 = index2 || index4
                if ((index1) && (index2)){
                    if (index3){
                        data.teacher = this.staff
                    }
                }
                data.page = 1
                data.pageSize = 999999
                console.log(data)
                const loading = this.$loading({
                    lock :true,
                    text:'',
                    spinner :'el-icon-loading',
                    background:'rgba(0, 0, 0, 0.7)'
                   })
                request({
                    url: "/student/getStudentList",
                    method: "post",
                    data: data
                }).then(res => {
                    loading.close()
                    // if (res.code == 200){
                    //     this.$alert('','下载成功')
                    // }
                    let temp = []
                    if (res.code == 200){
                        // this.$export.excel({
                        //     columns: ,
                        //     data: res.data.students,
                        //     title : '学生列表'
                        // })
                        console.log(res.data.students,'dsads')
                        excel.export([{label:'学生姓名',prop:'name'},{label:'学号',prop:'studentId'},{label:'性别',prop:'genderText'},{label:'校区',prop:'schoolText'},{label:'联系方式',prop:'contact'},{label:'课程',prop:'course'},{label:'状态',prop:'statusText'}],res.data.students,'学生列表')
                    }
                    



                })

            },

                        getSchoolList() {
                let data = {};
                data.page = 1
                data.pageSize = 99999
                request({
                    url: "/school/getSchoolList",
                    method: "post",
                    data
                }).then(res => {
                    this.schoolList = res.data.school;
                    // 返回数据
                });
            },

            uploadTemplate(file){

                let thisFile = event.currentTarget.files[0]
                     var rABS = false; //是否将文件读取为二进制字符串  
            const that = this
        FileReader.prototype.readAsBinaryString = function(f) {  
          var binary = "";  
          var rABS = false; //是否将文件读取为二进制字符串  
         var pt = this;  
         var workbook; //读取完成的数据  
         // var excelData;  
         var reader = new FileReader(); 
         reader.onprogress = function(e) { 
           let total = thisFile.size;
           this.progress = (e.loaded/total)*100;
           console.log( this.progress);
         };   
         reader.onload = function(e) {
            // var XLSX = require('xlsx');

            
           try {
             var bytes = new Uint8Array(reader.result);  
             var length = bytes.byteLength;  
             for(var i = 0; i < length; i++) {  
               binary += String.fromCharCode(bytes[i]);  
             }  
             if(rABS) {  
               workbook = XLSX.read(btoa(fixdata(binary)), { //手动转化  
                 type: 'base64'  
               });  
             }else {  
                               workbook = XLSX.read(binary, {  
                 type: 'binary'  
               });  
             } 
             // excelData = []; 
           } catch(e) {
             console.log('文件类型不正确',e);
             return;
           }
           let tempData = []
           var fromTo = '';
           for (var sheet in workbook.Sheets) {
             if (workbook.Sheets.hasOwnProperty(sheet)) {
               fromTo = workbook.Sheets[sheet]['!ref'];
               let temp = XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
               for (var i = 0 ; i < temp.length ; i++){
                    let xxx = {}
                    xxx.name = temp[i]['学生名字']
                    xxx.number = temp[i]['学号']
                    xxx.school = temp[i]['学校']
                    xxx.cellphone = temp[i]['手机']
                    xxx.gender = temp[i]['性别']
                    xxx.birthday = temp[i]['生日']
                    xxx.publicSchool = temp[i]['公立学校']
                    xxx.addrss = temp[i]['地址']
                    xxx.parent1 = temp[i]['家长1姓名']
                    xxx.parent1Relation = temp[i]['家长1关系']
                    xxx.parent1Cellphone = temp[i]['家长1手机']
                    xxx.parent2 = temp[i]['家长2姓名']
                    xxx.parent2Relation = temp[i]['家长2关系']
                    xxx.parent2Cellphone = temp[i]['家长2手机']
                    xxx.class1 = temp[i]['班级1名称']
                    xxx.class1Type = temp[i]['班级1付费方式']
                    xxx.class1Amount = temp[i]['班级1剩余课时']
                    xxx.class1ValidDate = temp[i]['班级1有效期']
                    xxx.class1AvgPrice = temp[i]['班级1单课价格']
                    xxx.class2 = temp[i]['班级2名称']
                    xxx.class2Type = temp[i]['班级2付费方式']
                    xxx.class2Amount = temp[i]['班级2剩余课时']
                    xxx.class2ValidDate = temp[i]['班级2有效期']    
                    xxx.class2AvgPrice = temp[i]['班级2单课价格']       
                    console.log(xxx.gender,'xxxx',i)        
                    if ((parseInt(xxx.gender) != 0) && (parseInt(xxx.gender) != 1)){
                        that.$alert('0为男，1为女','性别请填0或1')
                        return false
                    }
                    if (xxx.class1 != undefined){
                        if (xxx.class1Amount == undefined){
                            that.$alert('请填写剩余课时','班级信息不全')
                            return false
                        }
                        if (parseInt(xxx.class1Amount) == NaN){
                            that.$alert('余额为正数','班级信息不全')
                            return false
                        }
                        if ((parseInt(xxx.class1Type) != 0) && (parseInt(xxx.class1Type) != 1) && (parseInt(xxx.class1Type) != 2)){
                            that.$alert('班级付费方式请填写0,1或2','班级信息不全')
                            return false
                        }
                        if( xxx.class1ValidDate != undefined){
                            if (new Date(xxx.class1ValidDate) == 'Invalid Date'){
                                that.$alert('日期错误','班级信息不全')
                            }
                        }
                        if (parseInt(xxx.class1AvgPrice) == NaN){
                            that.$alert('课程单价为正数','班级信息不全')
                            return false
                        }
                    }
                    if (xxx.class2 != undefined){
                        if (xxx.class2Amount == undefined){
                            that.$alert('请填写剩余课时','班级信息不全')
                            return false
                        }
                         if (parseInt(xxx.class2Amount) == NaN){
                            that.$alert('剩余课时为整数','班级信息不全')
                            return false
                        }
                        if ((parseInt(xxx.class2Type) != 0) && (parseInt(xxx.class2Type) != 1) && (parseInt(xxx.class2Type) != 2)){
                            that.$alert('班级付费方式请填写0,1或2','班级信息不全')
                            return false
                        }
                        if( xxx.class2ValidDate != undefined){
                            if (new Date(xxx.class2ValidDate) == 'Invalid Date'){
                                that.$alert('日期错误','班级信息不全')
                            }
                        }
                        if (parseInt(xxx.class2Amount) == NaN){
                            that.$alert('余额为正数','班级信息不全')
                            return false
                        }
                        if (parseInt(xxx.class2AvgPrice) == NaN){
                            that.$alert('课程单价为正数','班级信息不全')
                            return false
                        }
                    }

                    if (xxx.parent1 != undefined){
                        if (xxx.parent1Relation == undefined){
                            that.$alert('请填写关系','家长信息不全')
                        }
                    }
                    if (xxx.parent2 != undefined){
                        if (xxx.parent2Relation == undefined){
                            that.$alert('请填写关系','家长信息不全')
                        }
                    }

                    tempData.push(xxx);
               }
               

               

             }
           }
           let data = {}
           data.data = tempData
           data.school = that.school
           console.log(tempData,'dsd')
           const loading = that.$loading({
            lock :true,
            text:'',
            spinner :'el-icon-loading',
            background:'rgba(0, 0, 0, 0.7)'
           })
            request({
                    url: "/student/importStudent",
                    method: "post",
                    data: data
                }).then(res => {
                    loading.close()
                    if (res.code == 200){
                        if (res.data.message == ''){
                            that.$alert('','导入成功！')
                            that.getDataList(that.dataSearch)
                        }
                        else{
                            that.$alert(res.data.message,'部分成功！')
                            that.getDataList(that.dataSearch)
                        }
                        
                    }
                })

         };
 
         reader.readAsArrayBuffer(f);  
 
       } 
  
       var reader = new FileReader();
       if(rABS) {  
         reader.readAsArrayBuffer(thisFile);  
       }else {  
         reader.readAsBinaryString(thisFile);  
       } 
 

            },
            load(){
                this.school = this.info.school[0]
            // this.school = this.info.school[0]._id
             this.staff = this.info.staff == undefined ? null : this.info.staff._id
            this.staffname = this.info.staff == undefined ? '' : this.info.staff.name
            this.rights = this.info.rights.map(function(e){return e.name})
            this.headquarter = (this.school.headquarter == 1 || this.school.headquarter == 2) ? 1 : 0
            this.dataSearch.page = 1;
            this.dataSearch.pageSize = 20;
            this.getDataList(this.dataSearch);
            console.log(this.headquarter,'sds')
            if (this.headquarter == 1){
                this.getSchoolList()
                this.dataSearch.school = this.school._id
                this.showSchool = true
            }
            let index1 = this.rights.indexOf('root') == -1
                let index2 = this.rights.indexOf('授课老师') != -1
                let index4 = this.rights.indexOf('教务老师') != -1
                let index3 = this.rights.indexOf('教务中心') == -1

                index2 = index2 || index4
                if ((index1) && (index2)){
                    if (index3){
                        data.teacher = this.staff
                        this.showSchool = false
                    }
                }

            }
        },
        beforeRouteEnter(to,from,next){
            if (to.meta.refresh == 'a'){
                to.meta.refresh = undefined
                next(v=>{
                v.load()
                })
            }
            else{
                next()
            }

        },
        created() {

            this.load()
        }
    };
</script>
